$(function() {
    var app;
    _.templateSettings = {
        interpolate : /\{\{(.+?)\}\}/g,      // print value: {{ value_name }}
        evaluate    : /\{%([\s\S]+?)%\}/g,   // excute code: {% code_to_execute %}
        escape      : /\{%-([\s\S]+?)%\}/g
    }; // excape H
    app = {
        pageIndex: [0, 0, 0],
        page: 15,
        tabIndex: 0,
        ajaxLoading: true,
        schemeListData : [],
        angle : 0,
        photoIndex : 0,
        initialize: function() {
            this.initDomNode();
            this.bindEvents();
        },
        initDomNode: function() {
            this.schemeManage = $('#schemeManage');
            this.schemeBody = $('.scheme-body', this.schemeManage);
            this.schemeInput = $('.scheme-input', this.schemeManage);
            this.schemeSearch = $('.scheme-search', this.schemeManage);
            this.schemeTree = $('.scheme-tree', this.schemeManage);

            this.schemeTab = $('.scheme-tab', this.schemeManage);
            this.schemeSummary = $('.scheme-summary', this.schemeManage);
            this.schemeMoney = $('.scheme-money', this.schemeManage);
            this.schemeList = $('.scheme-list', this.schemeManage);
            this.rmPic = $('.remove-picture', this.schemeManage);
            this.bdPic = $('.bind-picture', this.schemeManage);
            this.schemeChecked = $('.scheme-checked', this.schemeManage);
            this.schemePicBtn = $('.scheme-pic-btn', this.schemeManage);

            this.reimbursementTree = $('.scheme-tree', this.schemeManage);
            this.schemeReviewBtn = $('.scheme-review', this.schemeManage);
            this.schemeUnReviewBtn = $('.scheme-unreview', this.schemeManage);            
            this.schemeSelect = $('.scheme-select', this.schemeManage);
            this.loading = $('#dataLoading');
            this.popup = $('#myModal');
        },
        bindEvents: function() {
            var that;
            that = this;
            this.schemeSearch.on('click', function() { //执行案搜索菜单
                that.loading.show();
                that.requestSchemeTree();
            });

            this.schemeInput.on('keydown', function(e) { //执行案搜索菜单
                if (e.keyCode == 13) {
                    that.loading.show();
                    that.requestSchemeTree();
                    e.preventDefault();
                    return false;
                }
            });

            this.schemeTree.on('click', 'dt, dd', function(e) { //请求执行案id对应的图片列表 根节点为1 二级节点为2
                var val, tag;
                if (e.target != this) {
                    return;
                }
                that.loading.show();
                val = $.trim($(this).text());
                that.schemeId = val;
                that.schemeTree.find('on').removeClass('on');
                $(this).addClass('on').siblings().removeClass('on');
                that.schemeTab.find('li').first().addClass('active').siblings().removeClass('active');
                that.requestSchemeList(val);
                if(e.target.tagName.toUpperCase() == 'DT' && val.split('-').length ==2){
                    that.getMappingColumns();
                    that.schemeSelect.show();
                }else{
                    that.schemeSelect.hide();
                }
            });

            this.rmPic.on('click', function() { //删除图片
                that.loading.show();
                that.removePic();
            });

            this.bdPic.on('click', function() { //绑定图片
                that.loading.show();
                that.bindPic();
            });

            this.schemeTab.on('click', 'a', function(e) { //图片类型Tab切换
                e.preventDefault();
                that.switchTab($(this));
            });

            this.schemeChecked.on('change', function() { //全选图片
                $('input:checkbox', this.schemeList).prop('checked', $(this).is(':checked'));
            });

            this.schemeList.on('change', 'input:checkbox', function() { //图片列表中checkbox
                var checked;
                checked = $(this).is(':checked');
                !checked && that.schemeChecked.prop('checked', checked);
            });

            this.schemePicBtn.on('click', 'button', function() {
                var isBind;
                that.loading.show();
                isBind = $(this).hasClass('pic-bind-ok');
                isBind ? that.requestSchemeList() : that.requestunBindSchemeList();
                isBind ? that.bdPic.hide() : that.bdPic.css('display', 'inline-block');
            });

            $(window).scroll(function(){
                that.loadMoreCase();
            });

            this.schemeList.on('click', 'a', function(e){
                e.preventDefault();
                that.angle = 0;
                that.photoIndex = $(this).closest('li').index();
                $('img', that.popup).css({
                    WebkitTransform : 'rotate(0deg)',
                    MozTransform : 'rotate(0deg)',
                    MsTransform : 'rotate(0deg)',
                    OTransform : 'rotate(0deg)',
                    transform : 'rotate(0deg)'
                });
                that.popup.find('img').prop('src', $(this).children('img').prop('src'));
            });

            this.popup.on('click', 'a', function(e){
                var action;
                e.preventDefault();
                action = $(this).data('action');
                action = action.replace(/^\w/, function(str){
                    return str.toUpperCase();
                });
                that['pic'+action] && that['pic'+action]();
            });

            this.schemeSelect.on('change', function() {
                var val;
                val = $.trim($(this).val());
                that.schemeId = val;
                that.requestSchemeList(val, 3);
            });

            this.schemeReviewBtn.on('click', function() { //通过审核
                that.schemeReview();
            });

            this.schemeUnReviewBtn.on('click', function() { //通过审核
                that.schemeUnReview();
            });

            this.schemeList.on('click', '.edit-money', function(){
                that.editMoney($(this));
            });

            this.schemeList.on('click', '.update-money', function(){
                that.updateMoney($(this));
            });

            this.schemeList.on('click', '.to-location-pic', function(){
                that.toLocationPic($(this));
            });

            this.schemeList.on('click', '.to-unlocation-pic', function(){
                that.toUnLocationPic($(this));
            });
        },
        sendToServer: function(opt) {
            var base, url, type, that;
            that = this;
            base = 'http://218.89.135.237:9000/API/WEB/';
            url = base + opt.apiName;
            type = opt.type ? opt.type : 'GET';
            $.ajax({
                type: type,
                url: url,
                async: true,
                data: opt.data,
                // timeout: 15000,
                dataType: 'json'
            }).done(function(data) {
                // console.log(data);
                if (data.IsSuccessfully) {
                    opt.success && opt.success(data);
                } else {
                    opt.error && opt.error(data);
                    alert(data.ErrorMessage);
                }
                that.loading.hide();
            }).fail(function(xhr, ajaxOptions, thrownError) {
                // console.log(arguments);
                that.loading.hide();
                alert('error code: ' + xhr.status + '\n ajaxOptions:' + ajaxOptions + '\n message: ' + thrownError + '\n APIName:' + opt.apiName);
            });
        },
        requestSchemeTree: function() {
            var that, opt, id;
            id = $.trim(this.schemeInput.val());
            this.rootId = id;

            opt = {
                apiName: 'ApplyForReimbursement/GetReimbursementTree.ashx',
                data: {
                    programID: id
                },
                success: this.schemeTreeSuccess.bind(this)
            };

            this.sendToServer(opt);
        },
        schemeTreeSuccess: function(data) {
            data.id = this.rootId;
            this.schemeTree.html(_.template($('#schemeTreeTmpl').html(), data));
        },
        requestSchemeList: function(id, level) {
            var opt;
            id = id || this.schemeId;
            if(id==null || id ==''){
                this.loading.hide();
                return;
            }
            level = id.split('-').length;
            opt = {
                apiName: 'ApplyForReimbursement/GetDetailInfo.ashx',
                data: {
                    schemeID: id,
                    levelID: level
                },
                success: this.schemeListSuccess.bind(this)
            };
            this.sendToServer(opt);
        },
        requestunBindSchemeList: function(id) {
            var opt;
            id = id || this.rootId;
            if(id==null || id ==''){
                this.loading.hide();
                return;
            }
            id = id.split('-')[0];
            opt = {
                apiName: 'SchemeManagement/GetUnbindingPictures.ashx',
                data: {
                    schemeID: id
                },
                success: this.schemeListSuccess.bind(this)
            };

            // this.ajaxLoading = false;
            this.sendToServer(opt);
        },
        schemeListSuccess: function(data) {
            var page;
            data.schemeId = this.schemeId;
            this.paging(data); //分页
            this.schemeList.empty();
            this.schemeSummary.empty();
            this.schemeMoney.empty();
            this.schemeList.html(_.template($('#schemeListTmpl').html(), {
                initIndex : 0,
                Pictures: this.schemeListData[0][0]
            }));
            this.schemeBody.show();
            this.schemeChecked.prop('checked', false).parent().removeClass('checked');
            this.schemeTab.find('li').first().addClass('active').siblings().removeClass('active');
            this.pageIndex = [0, 0, 0];
            data.SchemeDetailInfo && this.setSchemeSummary(data.SchemeDetailInfo);
            data.TotalPictureCount && this.schemeMoney.html(_.template($('#schemeMoneyTmpl').html(), data));
        },
        paging: function(data) {
            this.handlePaging(data.PricePicture, 0);
            this.handlePaging(data.LocationPicture, 1);
            this.handlePaging(data.NoLocationPicture, 2);
            this.handlePaging(data.uploadFiles, 3);
        },
        handlePaging:function(data, index){
            var arr, result, page;
            arr = [];
            result = [];
            page = this.page;
            if (!data) {
                return;
            }
            for (var i = 0, l = data.length; i < l;) {
                arr.push(data[i]);
                i++;
                if (i % page == 0 || i == l) {
                    result.push(arr);
                    arr = [];
                }
            }
            // console.log(result);
            this.schemeListData[index] = result;
        },
        setSchemeSummary: function(str) {
            var arr, kv, data, key, val;
            arr = [];
            key = [];
            val = [];
            if (str != null && str != '') {
                arr = str.split(',');
                for (var i = 0, l = arr.length; i < l; i++) {
                    kv = arr[i].split(':');
                    key.push(kv[0]);
                    val.push(kv[1]);
                }
            }
            data = {
                key: key,
                val: val
            };
            this.schemeSummary.html(_.template($('#schemeSummaryTmpl').html(), data));
        },
        getCheckedPic: function() {
            var arr, pic;
            arr = [];
            pic = [];
            $('input:checked', this.schemeList).each(function(index, item) {
                $(item).is(':visible') && arr.push($(item).val());
                $(item).is(':visible') && pic.push($(item));
            });
            // console.log(arr);
            this.checkedPic = pic;
            return arr;
        },
        removePic: function() {
            var opt, id;
            id = this.getCheckedPic();
            opt = {
                apiName: 'SchemeManagement/DeleteSchemePicture.ashx',
                data: {
                    pictureID: id.join(',')
                },
                success: this.removePicSuccess.bind(this)
            };
            this.sendToServer(opt);
        },
        removePicSuccess: function(data) {
            var pic;
            pic = this.checkedPic;
            for (var i = 0, l = pic.length; i < l; i++) {
                pic[i].closest('.thumbnail').parent().remove();
            }
            // console.log('成功删除图片！');
        },
        bindPic: function() {
            var opt;
            data = this.getCheckedPic();
            opt = {
                apiName: 'SchemeManagement/BindingPicture.ashx',
                data: {
                    schemeDetailID: this.schemeId,
                    pictureID: data.join(',')
                },
                success: this.bindPicSuccess.bind(this)
            };
            this.sendToServer(opt);
        },
        bindPicSuccess: function(data) {
            alert('成功绑定图片！');
            this.schemeTab.find('li').first().addClass('active').siblings().removeClass('active');
            this.requestunBindSchemeList();
        },
        switchTab: function(target) {
            var index, arr;
            index = target.parent().index();
            // this.photoIndex=0;
            if(!this.schemeListData[0]){
                return;
            }
            target.parent().addClass('active').siblings().removeClass('active');
            this.tabIndex = index;
            this.pageIndex[index] = 0; 
            this.schemeList.html(_.template($('#schemeListTmpl').html(), {
                initIndex : 0,
                Pictures: this.schemeListData[index][0]
            }));

        },
        loadMoreCase:function(){
            var scrollBottom;
            scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();
            if(scrollBottom < 50){
                // if(this.ajaxLoading){
                //     return;
                // }
                // this.ajaxLoading = true;
                this.pageIndex[this.tabIndex]++;
                this.renderPage();
                // this.ajaxLoading = false;
            }
        },
        renderPage:function(){
            var index, data, len;
            index = this.pageIndex[this.tabIndex];

            data = this.schemeListData[this.tabIndex] && this.schemeListData[this.tabIndex][index];
            if(!data){
                return;
            }
            len = this.schemeList.find('.span4').length;
            this.schemeList.append(_.template($('#schemeListTmpl').html(), {initIndex:len, Pictures:data}));
        },
        picTurnLeft:function(){
            this.angle-=45;
            this.turnPic();
        },
        picTurnRight:function(){
            this.angle+=45;
            this.turnPic();
        },
        turnPic:function(){
            // console.log(this.angle);
            $('img', this.popup).css({
                WebkitTransform : 'rotate('+this.angle+'deg)',
                MozTransform : 'rotate('+this.angle+'deg)',
                MsTransform : 'rotate('+this.angle+'deg)',
                OTransform : 'rotate('+this.angle+'deg)',
                transform : 'rotate('+this.angle+'deg)'
            });
        },
        picPrev:function(){
            if(this.photoIndex<=0){
                alert('亲，已经是第一张图片了');
                return;
            }
            this.photoIndex-=1;
            this.picShow();
        },
        picNext:function(){
            if(this.photoIndex>=this.schemeList.find('li').length-1){
                alert('亲，已经是最后一张图片了');
                return;
            }
            this.photoIndex+=1;
            this.picShow();
        },
        picShow:function(){
            var src;
            src = this.schemeList.find('li').eq(this.photoIndex).find('img').prop('src');
            this.popup.find('img').prop('src', src);
        },
        getMappingColumns: function() {
            var opt;
            opt = {
                apiName: 'ApplyForReimbursement/GetMappingColumns.ashx',
                data: {
                    schemeID: this.schemeId
                },
                success: this.mappingColumnsSuccess.bind(this)
            };
            this.sendToServer(opt);
        },
        mappingColumnsSuccess: function(data) {
            this.schemeSelect.html(_.template($('#schemeSelectTmpl').html(), data));
        },
        schemeReview: function() {
            var opt, data;
            data = this.getCheckedPic();
            if(data.length > 100){
                alert('审核图片数量不能超过100张!');
                return;
            }
            opt = {
                apiName: 'ApplyForReimbursement/AuditedPicture.ashx',
                data: {
                    pictureID: data.join(',')
                },
                success: this.schemeReviewSuccess.bind(this)
            };
            this.sendToServer(opt);
        },
        schemeReviewSuccess: function(data) {
            alert('审核成功！');
            this.requestSchemeList();
        },
        schemeUnReview: function() {
            var opt, data;
            data = this.getCheckedPic();
            opt = {
                apiName: 'ApplyForReimbursement/CancelAuditedPicture.ashx',
                data: {
                    pictureID: data.join(',')
                },
                success: this.schemeUnReviewSuccess.bind(this)
            };
            this.sendToServer(opt);
        },
        schemeUnReviewSuccess: function(data) {
            alert('审核已成功撤销！');
            this.requestSchemeList();
        },
        editMoney:function(target){
            var m1, num, input, editBtn, updateBtn;
            m1 = target.closest('.caption').find('.item-price');
            num = $.trim(m1.find('strong').text());
            input = target.closest('.caption').find('.price-input');
            editBtn = target.closest('.caption').find('.edit-money');
            updateBtn = target.closest('.caption').find('.update-money');
            this.moneyField = m1;
            this.moneyInput = input;
            this.editMoneyBtn = editBtn;
            this.updateMoneyBtn = updateBtn;
            editBtn.hide();
            m1.hide();
            input.val(num).show();
            updateBtn.css({display:'inline-block'});
        },
        updateMoney:function(target){
            var opt, input, id, money, re;
            re = /^(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,2})?$/;
            id = target.data('id');
            input = target.closest('.caption').find('.price-input');
            money = $.trim(input.val());
            if(money =='' || !re.test(money)){
                alert('输入的金额格式不正确，请检查！');
                return;
            }
            this.money = money;
            opt = {
                apiName: 'ApplyForReimbursement/ModifyPicturePrice.ashx',
                data: {
                    pictureID: id,
                    price : money
                },
                success: this.updateMoneySuccess.bind(this)
            };
            this.sendToServer(opt);
        },
        updateMoneySuccess:function(data){
            this.moneyField.html('金额：&yen; <strong>'+this.money+'</strong>').show();
            this.moneyInput.hide();
            this.editMoneyBtn.show();
            this.updateMoneyBtn.hide();
            alert('更新金额成功!');
        },
        toLocationPic:function(target){
            var opt, id, type;
            id = target.data('id');
            type = target.data('pic-type');
            opt = {
                apiName: 'SchemeManagement/ChangePictureType.ashx',
                data: {
                    pictureID: id,
                    currentPictureType : type,
                    targetPictureType : 0
                },
                success: this.toLocationPicSuccess.bind(this)
            };
            this.sendToServer(opt);
        },
        toLocationPicSuccess:function(data){
            alert('已成功切换到定位照片！');
            this.requestSchemeList();
        },
        toUnLocationPic:function(target){
            var opt, id, type;
            id = target.data('id');
            type = target.data('pic-type');
            opt = {
                apiName: 'SchemeManagement/ChangePictureType.ashx',
                data: {
                    pictureID: id,
                    currentPictureType : type,
                    targetPictureType : 2
                },
                success: this.toUnLocationPicSuccess.bind(this)
            };
            this.sendToServer(opt);
        },
        toUnLocationPicSuccess:function(data){
            alert('已成功切换到非定位照片！');
            this.requestSchemeList();
        }
    };
    app.initialize();
    return app;
});